package effective.java.chapter1;

import java.util.Arrays;
import java.util.EmptyStackException;

/**
 * 自定义栈
 *
 * @author kkmystery
 * @version 1.0 2021/7/7
 * @since 1.0.0
 */
public class Stack {
    private Object[] elements;
    private int size = 0;
    private static final int DEFAULT_INITIAL_CAPACITY = 16;

    public Stack() {
        elements = new Object[DEFAULT_INITIAL_CAPACITY];
    }

    public void push(Object e) {
        ensureCapacity();
        elements[size++] = e;
    }

    public Object remove(Object e) {
        if (size == 0) {
            throw new EmptyStackException();
        }
        /*// 此写法发生内存泄漏
        return elements[--size];*/

        // 改良写法, 将弹出栈的实例赋空
        Object result = elements[--size];
        elements[size] = null;
        return result;
    }

    private void ensureCapacity() {
        if (elements.length == size) {
            // 扩容
            elements = Arrays.copyOf(elements, 2 * size + 1);
        }
    }

}
